#include "cli_ctx.h"
#include "cli_def.h"
#include "cli_core.h"
#include "stdio.h"
#include <stdlib.h>
#include <string.h>

CliCtx g_cli_ctx;

char g_CmdSysname[CMD_SYSNAME_SIZE] = "system";

char *cmd_get_sysname()
{
	if (NULL == g_cli_ctx.getSysname) {
		return g_CmdSysname;
	}

	return g_cli_ctx.getSysname();
}

void cmd_page_up() 
{
	if (NULL != g_cli_ctx.pageUp) {
		g_cli_ctx.pageUp();
	}
}

void cmd_page_down() 
{
	if (NULL != g_cli_ctx.pageDown) {
		g_cli_ctx.pageDown();
	}
}

int cmd_socket_send(int s, char *buf, int len, int flags) 
{
	if (NULL != g_cli_ctx.send) {
		return g_cli_ctx.send(s, buf, len, flags);
	}
	return send(s, buf, len, flags);
}

int cmd_socket_recv(int s, char *buf, int len, int flags) 
{
	if (NULL != g_cli_ctx.recv) {
		return g_cli_ctx.recv(s, buf, len, flags);
	}
	return recv(s, buf, len, flags);
}

int cmd_socket_close(int s) 
{
	if (NULL != g_cli_ctx.close) {
		return g_cli_ctx.close(s);
	}
#ifdef WIN32
	return closesocket(s);
#else
	return close(s);
#endif
}

int cmd_sleep(int ms) 
{
	if (NULL != g_cli_ctx.sleep) {
		return g_cli_ctx.sleep(ms);
	}
#ifdef WIN32
	Sleep(ms);
	return 0;
#else
	return usleep(ms);
#endif
}

int cmd_getchar(void) 
{
	if (NULL != g_cli_ctx.getchar) {
		return g_cli_ctx.getchar();
	}
	return getchar();
}

bool cmd_is_cfg_recover_over() 
{
	if (NULL != g_cli_ctx.isCfgRecoverOver) {
		return g_cli_ctx.isCfgRecoverOver();
	}
	return true;
}

int cmd_init(CliCtx *ctx)
{
    if (ctx) {
        memcpy(&g_cli_ctx, ctx, sizeof(CliCtx));
    }

    cmd_core_init();

    return 0;
}
